package com.skydoves.chatgpt.core.navigation

import androidx.navigation.NamedNavArgument
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.example.core_database.entities.Bot

sealed class ChatGPTScreens(
  val route: String,
  val navArguments: List<NamedNavArgument> = emptyList()
) {
  val name: String = route.appendArguments(navArguments)

  //user log in
  data object UserLogin : ChatGPTScreens("user log in")

  //user sign in
  data object UserSignin : ChatGPTScreens("user sign in")

  // channel screen
  data object Channel1 : ChatGPTScreens("channel1")
  data object Channel2 : ChatGPTScreens("channel2")
  data object Channel3 : ChatGPTScreens("channel3")
  data object Channel4 : ChatGPTScreens("channel4")
  data object Userchannel : ChatGPTScreens("userchannel")

  data object Channels : ChatGPTScreens("channels")

  // message screen
  data object Messages : ChatGPTScreens(
    route = "messages",
    navArguments = listOf(
      navArgument("botId") { type = NavType.StringType },
      navArgument("botName") { type = NavType.StringType },
      navArgument("conversationId") { type = NavType.StringType }
    )
  ) {
    // 更新 createRoute 方法，支持替换 botId 和 botName
    fun createRoute(bot: Bot): String {

      return name
        .replace("{${navArguments[0].name}}", bot.botId)
        .replace("{${navArguments[1].name}}", bot.botName)
        .replace("{${navArguments[2].name}}", bot.conversationId)
    }
  }
}

private fun String.appendArguments(navArguments: List<NamedNavArgument>): String {
  val mandatoryArguments = navArguments.filter { it.argument.defaultValue == null }
    .takeIf { it.isNotEmpty() }
    ?.joinToString(separator = "/", prefix = "/") { "{${it.name}}" }
    .orEmpty()
  val optionalArguments = navArguments.filter { it.argument.defaultValue != null }
    .takeIf { it.isNotEmpty() }
    ?.joinToString(separator = "&", prefix = "?") { "${it.name}={${it.name}}" }
    .orEmpty()
  return "$this$mandatoryArguments$optionalArguments"
}
